# -*- coding: utf-8 -*-
import hashlib
import json
import random
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now, utc_to_local

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://pay.drippayment.com/pay/onlinepay.json'

APP_CONF = {
    '0000025': {
        'API_KEY': 'A2CEDF2F7CD4AFF4',
    },
    '0000023': {
        'API_KEY': '6C1EFA70BF4D3D38',
    },
    '0000313': {
        'API_KEY': 'C021B443CF82C383',
    },
    '0000327': {
        'API_KEY': 'E2131D8C8D5F9668',
    },
    '0000442': {
        'API_KEY': 'EF07B2A38FD6D238',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['signData']
    params.pop('signData')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("dirpay_new sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _fix_pay_amount(pay, pay_amount):
    extend = json.loads(pay.extend or '{}')
    if pay_amount >= 10 and int(pay_amount) == pay_amount:
        discount = random.randint(1, 10)
        pay_amount = pay_amount - float(discount) / 100
        extend.update({'discount': str(float(discount) / 100)})
        order_db.fill_extend(pay.id, extend)
    return pay_amount


# 0002 ：微信
# 0003 ：支付宝
# 0004 ：QQ钱包
def _get_pay_type(service):
    if service == 'wxpay':
        payType = '0002'
    elif service == 'alipay':
        payType = '0003'
    elif service == 'qq':
        payType = '0004'
    else:
        payType = '0003'
    return payType


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    charge_resp = {}
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    pay_amount = _fix_pay_amount(pay, pay_amount)
    parameter_dict = OrderedDict((
        ('versionId', '001'),
        ('businessType', '1100'),
        ('transChanlName', _get_pay_type(service)),
        ('merId', app_id),
        ('orderId', str(pay.id)),
        ('transDate', local_now().strftime('%Y%m%d%H%M%S')),
        ('transAmount', str(pay_amount)),
        ('backNotifyUrl', '{}/pay/api/{}/dirpay_new/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('orderDesc', 'charge'),
        ('dev', str(pay.id)),
    ))
    parameter_dict['signData'] = generate_sign(parameter_dict, api_key)
    parameter_dict['signType'] = 'MD5'
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("dirpay_new create charge data: %s %s",
                 response.status_code, response.text)
    res_obj = json.loads(response.text)
    third_id = res_obj.get('ksPayOrderId')
    order_db.fill_third_id(pay.id, third_id)
    charge_resp.update({
        'charge_info': res_obj['codeUrl'].decode('gbk'),
    })
    return charge_resp


def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("dirpay_new notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['dev']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('dirpay_new event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['refcode']
    trade_no = data['ksPayOrderId']
    total_fee = float(data['transAmount'])

    discount = float(json.loads(pay.extend or '{}').get('discount', 0))
    extend = {
        'discount': discount,
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '00':
        _LOGGER.info('dirpay_new check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    order_id = str(pay_id)[2:]
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('versionId', '001'),
        ('businessType', '1200'),
        ('merId', app_id),
        ('transChanlName', '0003'),  # 0002 ：微信 0003 ：支付宝
        ('orderId', str(order_id)),
        ('transDate', utc_to_local(pay_order.updated_at).strftime('%Y%m%d%H%M%S')),
        ('ksPayOrderId', pay_order.third_id),
    ))
    parameter_dict['signData'] = generate_sign(parameter_dict, api_key)
    parameter_dict['signType'] = 'MD5'
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    if response.status_code == 200:
        # response text is a pure html text
        data = json.loads(response.text)
        print data
        trade_status = data['refcode']
        trade_no = data['ksPayOrderId']
        total_fee = float(data['transAmount'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == '00':
            _LOGGER.info('dirpay_new query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
            print("order process successfully. %s" % pay_order.id)
    else:
        _LOGGER.warn('dirpay_new data error, status_code: %s', response.status_code)
